<template>
  <div class="dashboard-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title-container">
        <h1 class="page-title">数据统计</h1>
      </div>
      <div class="header-controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          class="date-picker"
          @change="handleDateChange"
        />
        <div class="current-time">{{ formatCurrentTime() }}</div>
        <el-button
          icon="el-icon-refresh"
          class="refresh-btn"
          @click="refreshData"
        />
      </div>
    </div>

    <!-- 核心数据汇总卡片（发货到货+检验总览） -->
    <div class="stats-cards">
      <div class="stat-card card-shipment">
        <div class="card-header">
          <span class="card-title">今日发货总量</span>
          <i class="el-icon-box card-icon" />
        </div>
        <div class="card-value">
          <div class="digital-value">{{ formatNumber(dailyShipmentTotal) }}</div>
          <span class="unit">吨</span>
        </div>
        <div class="card-footer">
          <span class="trend-up">↑ 5.2%</span>
          <span class="compared">较昨日</span>
        </div>
      </div>

      <div class="stat-card card-arrival">
        <div class="card-header">
          <span class="card-title">今日到货总量</span>
          <i class="el-icon-box card-icon" />
        </div>
        <div class="card-value">
          <div class="digital-value">{{ formatNumber(dailyArrivalTotal) }}</div>
          <span class="unit">吨</span>
        </div>
        <div class="card-footer">
          <span class="trend-down">↓ 2.1%</span>
          <span class="compared">较昨日</span>
        </div>
      </div>

      <div class="stat-card card-inspect-total">
        <div class="card-header">
          <span class="card-title">总检验数</span>
          <i class="el-icon-check card-icon" />
        </div>
        <div class="card-value">
          <div class="digital-value">{{ formatNumber(totalInspected) }}</div>
          <span class="unit">批次</span>
        </div>
        <div class="card-footer">
          <span class="trend-up">↑ 3.8%</span>
          <span class="compared">较昨日</span>
        </div>
      </div>

      <div class="stat-card card-unqualified-total">
        <div class="card-header">
          <span class="card-title">总不合格数</span>
          <i class="el-icon-close card-icon" />
        </div>
        <div class="card-value">
          <div class="digital-value">{{ formatNumber(totalUnqualified) }}</div>
          <span class="unit">批次</span>
        </div>
        <div class="card-footer">
          <span class="trend-down">↓ 1.5%</span>
          <span class="compared">较昨日</span>
        </div>
      </div>

      <div class="stat-card card-qualified-rate">
        <div class="card-header">
          <span class="card-title">整体合格率</span>
          <i class="el-icon-circle-check card-icon" />
        </div>
        <div class="card-value">
          <div class="digital-value">{{ formatNumber(overallQualifiedRate, 2) }}</div>
          <span class="unit">%</span>
        </div>
        <div class="card-footer">
          <span class="trend-up">↑ 0.6%</span>
          <span class="compared">较昨日</span>
        </div>
      </div>
    </div>

    <!-- 产品检验详情卡片（分产品展示） -->
    <div class="section-title">产品检验详情</div>
    <div class="inspection-detail-cards">
      <div
        v-for="(item, index) in productInspectionData"
        :key="index"
        class="detail-card"
        :style="{ '--card-color': detailCardColors[index] }"
      >
        <div class="detail-card-header">
          <span class="product-name">{{ item.name }}</span>
        </div>
        <div class="detail-card-body">
          <div class="detail-item">
            <span class="item-label">检验数</span>
            <span class="item-value">{{ formatNumber(item.inspectedNum) }} 批次</span>
          </div>
          <div class="detail-item">
            <span class="item-label">不合格数</span>
            <span class="item-value unqualified">{{ formatNumber(item.unqualifiedNum) }} 批次</span>
          </div>
          <div class="detail-item">
            <span class="item-label">合格率</span>
            <span class="item-value rate">{{ formatNumber(item.qualifiedRate, 2) }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 原有业务图表区（发货到货相关） -->
    <div class="section-title">业务趋势分析</div>
    <div class="charts-row">
      <div class="chart-card">
        <div class="chart-header">
          <span>每日发货量按种类分布</span>
          <el-select
            v-model="dailyShipmentType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleShipmentTypeChange"
          >
            <el-option label="柱状图" value="bar" />
            <el-option label="折线图" value="line" />
            <el-option label="饼图" value="pie" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="dailyShipmentChart" class="chart" />
        </div>
      </div>

      <div class="chart-card">
        <div class="chart-header">
          <span>每日到货量按种类分布</span>
          <el-select
            v-model="dailyArrivalType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleArrivalTypeChange"
          >
            <el-option label="柱状图" value="bar" />
            <el-option label="折线图" value="line" />
            <el-option label="饼图" value="pie" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="dailyArrivalChart" class="chart" />
        </div>
      </div>
    </div>

    <!-- 新增检验数据图表区 -->
    <div class="section-title">检验质量分析</div>
    <div class="charts-row">
      <div class="chart-card">
        <div class="chart-header">
          <span>各产品检验数 vs 不合格数</span>
          <el-select
            v-model="inspectionCompareType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleInspectionCompareChange"
          >
            <el-option label="柱状图" value="bar" />
            <el-option label="折线图" value="line" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="inspectionCompareChart" class="chart" />
        </div>
      </div>

      <div class="chart-card">
        <div class="chart-header">
          <span>各产品不合格率分布</span>
          <el-select
            v-model="unqualifiedRateType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleUnqualifiedRateChange"
          >
            <el-option label="环形图" value="pie" />
            <el-option label="柱状图" value="bar" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="unqualifiedRateChart" class="chart" />
        </div>
      </div>
    </div>

    <!-- 每周/每月趋势图表（保留原有） -->
    <div class="section-title">周期趋势汇总</div>
    <div class="charts-row">
      <div class="chart-card">
        <div class="chart-header">
          <span>每周发货与到货趋势</span>
          <el-select
            v-model="weeklyChartType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleWeeklyTypeChange"
          >
            <el-option label="柱状图" value="bar" />
            <el-option label="折线图" value="line" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="weeklyChart" class="chart" />
          <el-table
            :data="weeklyTableData"
            size="mini"
            class="scroll-board"
            border
          >
            <el-table-column prop="week" label="周期" align="center" />
            <el-table-column prop="data" label="数据" align="center" />
          </el-table>
        </div>
      </div>

      <div class="chart-card">
        <div class="chart-header">
          <span>每月发货与到货趋势</span>
          <el-select
            v-model="monthlyChartType"
            placeholder="选择图表类型"
            size="small"
            class="chart-type-select"
            @change="handleMonthlyTypeChange"
          >
            <el-option label="柱状图" value="bar" />
            <el-option label="折线图" value="line" />
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="monthlyChart" class="chart" />
          <div class="percentage-container">
            <el-progress
              type="circle"
              :percentage="monthlyCompletionRate"
              :width="100"
              color="#f7b731"
              class="percentage-ring"
            />
            <div class="percentage-text">月度完成率</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 修复：适配 ECharts 4.x/5.x 导入语法，优先用全局实例（window.echarts），局部导入兜底
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      // 日期范围
      dateRange: null,
      dateShortcuts: [
        { text: '今天', value: () => [new Date(), new Date()] },
        { text: '本周', value: () => { const d = new Date(); return [new Date(d.setDate(d.getDate() - d.getDay())), new Date()] } },
        { text: '本月', value: () => { const d = new Date(); return [new Date(d.setDate(1)), new Date()] } }
      ],
      currentTimeInterval: null,

      // 原有业务数据
      dailyShipmentTotal: 1258,
      dailyArrivalTotal: 986,
      weeklyShipmentTotal: 7852,
      monthlyShipmentTotal: 32560,
      monthlyCompletionRate: 78,

      // 图表类型选择
      dailyShipmentType: 'bar',
      dailyArrivalType: 'bar',
      weeklyChartType: 'bar',
      monthlyChartType: 'line',
      inspectionCompareType: 'bar',
      unqualifiedRateType: 'pie',

      // 原有图表模拟数据
      dailyShipmentData: {
        categories: ['高硫焦', '低硫焦', '超高硫焦', '煅烧焦', '增碳剂'],
        data: [320, 280, 180, 220, 150],
        codes: ['', '', '', '', '']
      },
      dailyArrivalData: { categories: ['高硫焦', '低硫焦', '超高硫焦', '煅烧焦', '增碳剂'], data: [280, 210, 150, 190, 120] },
      weeklyData: { weeks: ['第1周', '第2周', '第3周', '第4周'], shipment: [1850, 2100, 1980, 2350], arrival: [1650, 1900, 1820, 2100] },
      monthlyData: { months: ['1月', '2月', '3月', '4月', '5月', '6月'], shipment: [7500, 8200, 7900, 9100, 8800, 9500], arrival: [6800, 7500, 7200, 8300, 8000, 8700] },
      weeklyTableData: [
        { week: '第1周', data: '发货1,850吨 / 到货1,650吨' },
        { week: '第2周', data: '发货2,100吨 / 到货1,900吨' },
        { week: '第3周', data: '发货1,980吨 / 到货1,820吨' },
        { week: '第4周', data: '发货2,350吨 / 到货2,100吨' }
      ],

      // 新增检验数据
      productInspectionData: [
        { name: '石油焦', inspectedNum: 320, unqualifiedNum: 12, qualifiedRate: ((320 - 12) / 320 * 100).toFixed(2) * 1 },
        { name: '煅后焦', inspectedNum: 280, unqualifiedNum: 8, qualifiedRate: ((280 - 8) / 280 * 100).toFixed(2) * 1 },
        { name: '生坯', inspectedNum: 250, unqualifiedNum: 15, qualifiedRate: ((250 - 15) / 250 * 100).toFixed(2) * 1 },
        { name: '熟坯', inspectedNum: 230, unqualifiedNum: 7, qualifiedRate: ((230 - 7) / 230 * 100).toFixed(2) * 1 },
        { name: '沥青', inspectedNum: 190, unqualifiedNum: 5, qualifiedRate: ((190 - 5) / 190 * 100).toFixed(2) * 1 }
      ],
      detailCardColors: [
        '#3b82f6', // 石油焦-蓝
        '#8b5cf6', // 煅后焦-紫
        '#f7b731', // 生坯-黄
        '#10b981', // 熟坯-绿
        '#ec4899' // 沥青-粉
      ],

      // 图表实例
      dailyShipmentChartObj: null,
      dailyArrivalChartObj: null,
      weeklyChartObj: null,
      monthlyChartObj: null,
      inspectionCompareChartObj: null,
      unqualifiedRateChartObj: null,

      // 修复：存储实际使用的 echarts 实例（全局/局部）
      echartsInstance: null
    }
  },
  computed: {
    // 检验汇总数据（计算得出）
    totalInspected() {
      return this.productInspectionData.reduce((sum, item) => sum + item.inspectedNum, 0)
    },
    totalUnqualified() {
      return this.productInspectionData.reduce((sum, item) => sum + item.unqualifiedNum, 0)
    },
    overallQualifiedRate() {
      const rate = ((this.totalInspected - this.totalUnqualified) / this.totalInspected) * 100
      return rate.toFixed(2) * 1 // 转为数字，避免字符串拼接
    }
  },
  mounted() {
    // 修复：初始化 echarts 实例（优先全局，再局部）
    this.echartsInstance = window.echarts || echarts
    if (!this.echartsInstance) {
      this.$message.error('ECharts 未加载，请检查依赖是否安装！')
      return
    }

    // 初始化定时器
    this.currentTimeInterval = setInterval(() => {
      this.$forceUpdate() // 强制更新时间显示
    }, 1000)

    // 初始化图表
    this.initCharts()

    // 监听窗口大小变化重绘图表
    window.addEventListener('resize', this.handleWindowResize)
  },
  beforeDestroy() {
    // 清除定时器
    if (this.currentTimeInterval) {
      clearInterval(this.currentTimeInterval)
    }

    // 销毁图表
    this.destroyCharts()

    // 移除事件监听
    window.removeEventListener('resize', this.handleWindowResize)
  },
  methods: {
    // 窗口resize处理（单独提取方法，避免重复代码）
    handleWindowResize() {
      this.dailyShipmentChartObj && this.dailyShipmentChartObj.resize()
      this.dailyArrivalChartObj && this.dailyArrivalChartObj.resize()
      this.weeklyChartObj && this.weeklyChartObj.resize()
      this.monthlyChartObj && this.monthlyChartObj.resize()
      this.inspectionCompareChartObj && this.inspectionCompareChartObj.resize()
      this.unqualifiedRateChartObj && this.unqualifiedRateChartObj.resize()
    },

    // 当前时间格式化
    formatCurrentTime() {
      const d = new Date()
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
    },

    // 数字格式化（支持保留小数）
    formatNumber(num, decimal = 0) {
      return num.toFixed(decimal).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 辅助函数：精准查找数组索引
    contains(arr, dst) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === dst) return i
      }
      return -1
    },

    // 辅助函数：处理渐变数据格式
    attackSourcesDataFmt(sData) {
      const attackSourcesColor = [
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#3b82f6' }, { offset: 1, color: '#60a5fa' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#8b5cf6' }, { offset: 1, color: '#a78bfa' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#f7b731' }, { offset: 1, color: '#ffee96' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#10b981' }, { offset: 1, color: '#34d399' }])
      ]
      return sData.map((item, i) => ({
        value: item,
        itemStyle: { color: i > 3 ? attackSourcesColor[3] : attackSourcesColor[i] }
      }))
    },

    // ---------------------- 图表更新方法 ----------------------
    // 每日发货量图表
    updateDailyShipmentChart() {
      if (!this.dailyShipmentChartObj) return
      const attaData = this.dailyShipmentData.data.map(num => num.toFixed(2))
      const attaName = this.dailyShipmentData.categories
      const attackSourcesColor1 = ['#3b82f6', '#8b5cf6', '#f7b731', '#10b981', '#ec4899']
      const attackSourcesColor = [
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#3b82f6' }, { offset: 1, color: '#60a5fa' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#8b5cf6' }, { offset: 1, color: '#a78bfa' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#f7b731' }, { offset: 1, color: '#ffee96' }]),
        new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#10b981' }, { offset: 1, color: '#34d399' }])
      ]

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' },
          formatter: (params) => {
            const type = params.dataIndex >= 0 ? attaName[params.dataIndex] : params.name
            return `${type}<br/>发货量：${params.value} 吨`
          }
        },
        legend: {
          show: this.dailyShipmentType !== 'pie',
          data: ['每日发货量(吨)'],
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color: attackSourcesColor[0].colorStops[0].color }
        },
        grid: {
          left: this.dailyShipmentType === 'bar' ? '15%' : '5%',
          right: this.dailyShipmentType === 'bar' ? '10%' : '5%',
          bottom: this.dailyShipmentType !== 'pie' ? '15%' : '5%',
          top: '8%',
          containLabel: true
        },
        xAxis: [],
        yAxis: [],
        series: []
      }

      // 柱状图
      if (this.dailyShipmentType === 'bar') {
        Object.assign(option, {
          xAxis: {
            type: 'value',
            splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
            axisLabel: { show: true, color: '#64748b', fontSize: 10 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
            min: 0,
            max: Math.max(...this.dailyShipmentData.data) * 1.1
          },
          yAxis: [
            {
              type: 'category',
              inverse: true,
              axisLine: { show: false },
              axisTick: { show: false },
              axisPointer: { label: { show: true, backgroundColor: '#fff', borderColor: '#e2e8f0' }},
              padding: [5, 0, 0, 0],
              position: 'right',
              data: attaName,
              axisLabel: {
                margin: 30,
                fontSize: 10,
                align: 'left',
                color: '#475569',
                rich: {
                  nt1: { color: '#fff', backgroundColor: attackSourcesColor1[0], width: 13, height: 13, fontSize: 10, align: 'center', borderRadius: '50%', lineHeight: 13, padding: [0, 1, 0, 1] },
                  nt2: { color: '#fff', backgroundColor: attackSourcesColor1[1], width: 13, height: 13, fontSize: 10, align: 'center', borderRadius: '50%', lineHeight: 13, padding: [0, 1, 0, 1] },
                  nt3: { color: '#fff', backgroundColor: attackSourcesColor1[2], width: 13, height: 13, fontSize: 10, align: 'center', borderRadius: '50%', lineHeight: 13, padding: [0, 1, 0, 1] },
                  nt: { color: '#fff', backgroundColor: attackSourcesColor1[3], width: 13, height: 13, fontSize: 10, align: 'center', borderRadius: '50%', lineHeight: 13, padding: [0, 1, 0, 1] }
                },
                formatter: function (value) {
                  const index = this.contains(attaName, value)
                  if (index === -1) return value
                  const rank = index + 1
                  const styleKey = rank <= 3 ? `nt${rank}` : 'nt'
                  return [`{${styleKey}|${rank}}`].join('\n')
                }.bind(this)
              }
            },
            {
              type: 'category',
              offset: -10,
              position: 'left',
              axisLine: { show: false },
              inverse: false,
              axisTick: { show: false },
              data: attaName,
              axisLabel: { fontSize: 10, color: '#64748b' }
            }
          ],
          series: [
            {
              name: '每日发货量(吨)',
              type: 'bar',
              data: this.attackSourcesDataFmt(attaData),
              barWidth: 12,
              z: 10,
              label: {
                show: true,
                position: 'left',
                distance: 5,
                color: '#64748b',
                fontSize: 10,
                formatter: (params) => params.value.value
              }
            }
          ]
        })
      }

      // 折线图
      if (this.dailyShipmentType === 'line') {
        Object.assign(option, {
          xAxis: {
            type: 'category',
            data: attaName,
            splitLine: { show: false },
            axisLabel: { show: true, color: '#64748b', fontSize: 10, rotate: 15 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
          },
          yAxis: {
            type: 'value',
            splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
            axisLabel: { show: true, color: '#64748b', fontSize: 10 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
            min: 0
          },
          series: [
            {
              name: '每日发货量(吨)',
              type: 'line',
              data: attaData,
              smooth: true,
              lineStyle: { width: 3, color: attackSourcesColor[0] },
              itemStyle: { color: attackSourcesColor1[0], borderWidth: 2, borderColor: '#fff' },
              symbol: 'circle',
              symbolSize: 8,
              label: {
                show: true,
                position: 'top',
                color: '#64748b',
                fontSize: 10
              }
            }
          ]
        })
      }

      // 饼图
      if (this.dailyShipmentType === 'pie') {
        Object.assign(option, {
          series: [
            {
              name: '每日发货量(吨)',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['50%', '50%'],
              data: attaName.map((name, i) => ({ name, value: attaData[i] })),
              itemStyle: {
                color: (params) => attackSourcesColor1[params.dataIndex % attackSourcesColor1.length],
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c}吨',
                fontSize: 10,
                color: '#64748b'
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 20,
                lineStyle: { color: '#e2e8f0' }
              }
            }
          ]
        })
      }

      this.dailyShipmentChartObj.setOption(option)
    },

    // 每日到货量图表
    updateDailyArrivalChart() {
      if (!this.dailyArrivalChartObj) return
      const attaData = this.dailyArrivalData.data.map(num => num.toFixed(2))
      const attaName = this.dailyArrivalData.categories
      const color = '#10b981'
      const gradientColor = new this.echartsInstance.graphic.LinearGradient(0, 1, 1, 1, [{ offset: 0, color: '#10b981' }, { offset: 1, color: '#34d399' }])

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' },
          formatter: (params) => `${params.name}<br/>到货量：${params.value} 吨`
        },
        legend: {
          show: this.dailyArrivalType !== 'pie',
          data: ['每日到货量(吨)'],
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color }
        },
        grid: {
          left: this.dailyArrivalType === 'bar' ? '15%' : '5%',
          right: this.dailyArrivalType === 'bar' ? '10%' : '5%',
          bottom: this.dailyArrivalType !== 'pie' ? '15%' : '5%',
          top: '8%',
          containLabel: true
        },
        xAxis: [],
        yAxis: [],
        series: []
      }

      // 柱状图
      if (this.dailyArrivalType === 'bar') {
        Object.assign(option, {
          xAxis: {
            type: 'value',
            splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
            axisLabel: { show: true, color: '#64748b', fontSize: 10 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
            min: 0,
            max: Math.max(...this.dailyArrivalData.data) * 1.1
          },
          yAxis: {
            type: 'category',
            inverse: true,
            axisLine: { show: false },
            axisTick: { show: false },
            data: attaName,
            axisLabel: { fontSize: 10, color: '#475569' }
          },
          series: [
            {
              name: '每日到货量(吨)',
              type: 'bar',
              data: attaData,
              barWidth: 12,
              itemStyle: { color: gradientColor },
              label: {
                show: true,
                position: 'left',
                distance: 5,
                color: '#64748b',
                fontSize: 10
              }
            }
          ]
        })
      }

      // 折线图
      if (this.dailyArrivalType === 'line') {
        Object.assign(option, {
          xAxis: {
            type: 'category',
            data: attaName,
            splitLine: { show: false },
            axisLabel: { show: true, color: '#64748b', fontSize: 10, rotate: 15 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
          },
          yAxis: {
            type: 'value',
            splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
            axisLabel: { show: true, color: '#64748b', fontSize: 10 },
            axisTick: { show: false },
            axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
            min: 0
          },
          series: [
            {
              name: '每日到货量(吨)',
              type: 'line',
              data: attaData,
              smooth: true,
              lineStyle: { width: 3, color },
              itemStyle: { color, borderWidth: 2, borderColor: '#fff' },
              symbol: 'circle',
              symbolSize: 8,
              label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
            }
          ]
        })
      }

      // 饼图
      if (this.dailyArrivalType === 'pie') {
        Object.assign(option, {
          series: [
            {
              name: '每日到货量(吨)',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['50%', '50%'],
              data: attaName.map((name, i) => ({ name, value: attaData[i] })),
              itemStyle: {
                color: (params) => [`#10b981`, `#34d399`, `#6ee7b7`, `#a7f3d0`, `#d1fae5`][params.dataIndex],
                borderColor: '#fff',
                borderWidth: 2
              },
              label: { show: true, position: 'outside', formatter: '{b}: {c}吨', fontSize: 10, color: '#64748b' },
              labelLine: { show: true, length: 10, length2: 20, lineStyle: { color: '#e2e8f0' }}
            }
          ]
        })
      }

      this.dailyArrivalChartObj.setOption(option)
    },

    // 检验数vs不合格数对比图表
    updateInspectionCompareChart() {
      if (!this.inspectionCompareChartObj) return
      const productNames = this.productInspectionData.map(item => item.name)
      const inspectedData = this.productInspectionData.map(item => item.inspectedNum)
      const unqualifiedData = this.productInspectionData.map(item => item.unqualifiedNum)
      const colors = ['#3b82f6', '#ef4444']

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' }
        },
        legend: {
          data: ['检验数', '不合格数'],
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color: (params) => colors[params.dataIndex] }
        },
        grid: { left: '5%', right: '5%', bottom: '15%', top: '8%', containLabel: true },
        xAxis: {
          type: 'category',
          data: productNames,
          splitLine: { show: false },
          axisLabel: { show: true, color: '#64748b', fontSize: 10, rotate: 15 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
        },
        yAxis: {
          type: 'value',
          splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
          axisLabel: { show: true, color: '#64748b', fontSize: 10 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
          min: 0
        },
        series: [
          {
            name: '检验数',
            type: this.inspectionCompareType,
            data: inspectedData,
            itemStyle: { color: colors[0] },
            lineStyle: this.inspectionCompareType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          },
          {
            name: '不合格数',
            type: this.inspectionCompareType,
            data: unqualifiedData,
            itemStyle: { color: colors[1] },
            lineStyle: this.inspectionCompareType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          }
        ]
      }

      this.inspectionCompareChartObj.setOption(option)
    },

    // 不合格率分布图表
    updateUnqualifiedRateChart() {
      if (!this.unqualifiedRateChartObj) return
      const productNames = this.productInspectionData.map(item => item.name)
      const unqualifiedRate = this.productInspectionData.map(item => {
        const rate = 100 - item.qualifiedRate
        return rate.toFixed(2)
      })
      const colors = ['#ef4444', '#f87171', '#fca5a5', '#fecaca', '#fee2e2']

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' },
          formatter: (params) => `${params.name}<br/>不合格率：${params.value}%`
        },
        legend: {
          show: this.unqualifiedRateType === 'bar',
          data: productNames,
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color: (params) => colors[params.dataIndex % colors.length] }
        },
        grid: this.unqualifiedRateType === 'bar' ? { left: '5%', right: '5%', bottom: '15%', top: '8%', containLabel: true } : {},
        xAxis: this.unqualifiedRateType === 'bar' ? {
          type: 'category',
          data: productNames,
          splitLine: { show: false },
          axisLabel: { show: true, color: '#64748b', fontSize: 10, rotate: 15 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
        } : [],
        yAxis: this.unqualifiedRateType === 'bar' ? {
          type: 'value',
          splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
          axisLabel: { show: true, color: '#64748b', fontSize: 10, formatter: '{value}%' },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
          min: 0
        } : [],
        series: [
          {
            name: '不合格率',
            type: this.unqualifiedRateType === 'pie' ? 'pie' : 'bar',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            data: productNames.map((name, i) => ({ name, value: unqualifiedRate[i] })),
            itemStyle: {
              color: (params) => colors[params.dataIndex % colors.length],
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: this.unqualifiedRateType === 'pie' ? 'outside' : 'top',
              formatter: this.unqualifiedRateType === 'pie' ? '{b}: {c}%' : '{c}%',
              fontSize: 10,
              color: '#64748b'
            },
            labelLine: this.unqualifiedRateType === 'pie' ? {
              show: true,
              length: 10,
              length2: 20,
              lineStyle: { color: '#e2e8f0' }
            } : {}
          }
        ]
      }

      this.unqualifiedRateChartObj.setOption(option)
    },

    // 每周趋势图表
    updateWeeklyChart() {
      if (!this.weeklyChartObj) return
      const weeks = this.weeklyData.weeks
      const shipmentData = this.weeklyData.shipment
      const arrivalData = this.weeklyData.arrival
      const colors = ['#3b82f6', '#10b981']

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' }
        },
        legend: {
          data: ['发货量', '到货量'],
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color: (params) => colors[params.dataIndex] }
        },
        grid: { left: '5%', right: '5%', bottom: '15%', top: '8%', containLabel: true },
        xAxis: {
          type: 'category',
          data: weeks,
          splitLine: { show: false },
          axisLabel: { show: true, color: '#64748b', fontSize: 10 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
        },
        yAxis: {
          type: 'value',
          splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
          axisLabel: { show: true, color: '#64748b', fontSize: 10 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
          min: 0
        },
        series: [
          {
            name: '发货量',
            type: this.weeklyChartType,
            data: shipmentData,
            itemStyle: { color: colors[0] },
            lineStyle: this.weeklyChartType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          },
          {
            name: '到货量',
            type: this.weeklyChartType,
            data: arrivalData,
            itemStyle: { color: colors[1] },
            lineStyle: this.weeklyChartType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          }
        ]
      }

      this.weeklyChartObj.setOption(option)
    },

    // 每月趋势图表
    updateMonthlyChart() {
      if (!this.monthlyChartObj) return
      const months = this.monthlyData.months
      const shipmentData = this.monthlyData.shipment
      const arrivalData = this.monthlyData.arrival
      const colors = ['#3b82f6', '#10b981']

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e2e8f0',
          borderWidth: 1,
          textStyle: { fontSize: 12, color: '#334155' }
        },
        legend: {
          data: ['发货量', '到货量'],
          bottom: 0,
          textStyle: { fontSize: 10, color: '#64748b' },
          itemStyle: { color: (params) => colors[params.dataIndex] }
        },
        grid: { left: '5%', right: '20%', bottom: '15%', top: '8%', containLabel: true },
        xAxis: {
          type: 'category',
          data: months,
          splitLine: { show: false },
          axisLabel: { show: true, color: '#64748b', fontSize: 10 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }}
        },
        yAxis: {
          type: 'value',
          splitLine: { show: true, lineStyle: { color: '#f1f5f9' }},
          axisLabel: { show: true, color: '#64748b', fontSize: 10 },
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#e2e8f0' }},
          min: 0
        },
        series: [
          {
            name: '发货量',
            type: this.monthlyChartType,
            data: shipmentData,
            itemStyle: { color: colors[0] },
            lineStyle: this.monthlyChartType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          },
          {
            name: '到货量',
            type: this.monthlyChartType,
            data: arrivalData,
            itemStyle: { color: colors[1] },
            lineStyle: this.monthlyChartType === 'line' ? { width: 3 } : {},
            symbol: 'circle',
            symbolSize: 8,
            label: { show: true, position: 'top', color: '#64748b', fontSize: 10 }
          }
        ]
      }

      this.monthlyChartObj.setOption(option)
    },

    // ---------------------- 事件处理方法 ----------------------
    handleShipmentTypeChange() {
      this.updateDailyShipmentChart()
    },
    handleArrivalTypeChange() {
      this.updateDailyArrivalChart()
    },
    handleInspectionCompareChange() {
      this.updateInspectionCompareChart()
    },
    handleUnqualifiedRateChange() {
      this.updateUnqualifiedRateChart()
    },
    handleWeeklyTypeChange() {
      this.updateWeeklyChart()
    },
    handleMonthlyTypeChange() {
      this.updateMonthlyChart()
    },
    handleDateChange() {
      // 实际项目中可根据日期范围请求接口，这里用模拟数据刷新图表
      this.refreshData()
    },
    refreshData() {
      // 模拟刷新效果
      this.$message.success('数据刷新成功')
      this.updateDailyShipmentChart()
      this.updateDailyArrivalChart()
      this.updateInspectionCompareChart()
      this.updateUnqualifiedRateChart()
      this.updateWeeklyChart()
      this.updateMonthlyChart()
    },

    // 初始化图表（修复：使用统一的 echartsInstance）
    initCharts() {
      if (!this.echartsInstance) return

      // 初始化图表实例
      this.dailyShipmentChartObj = this.echartsInstance.init(this.$refs.dailyShipmentChart)
      this.dailyArrivalChartObj = this.echartsInstance.init(this.$refs.dailyArrivalChart)
      this.weeklyChartObj = this.echartsInstance.init(this.$refs.weeklyChart)
      this.monthlyChartObj = this.echartsInstance.init(this.$refs.monthlyChart)
      this.inspectionCompareChartObj = this.echartsInstance.init(this.$refs.inspectionCompareChart)
      this.unqualifiedRateChartObj = this.echartsInstance.init(this.$refs.unqualifiedRateChart)

      // 初始化所有图表
      this.updateDailyShipmentChart()
      this.updateDailyArrivalChart()
      this.updateInspectionCompareChart()
      this.updateUnqualifiedRateChart()
      this.updateWeeklyChart()
      this.updateMonthlyChart()
    },

    // 销毁图表
    destroyCharts() {
      this.dailyShipmentChartObj && this.dailyShipmentChartObj.dispose()
      this.dailyArrivalChartObj && this.dailyArrivalChartObj.dispose()
      this.weeklyChartObj && this.weeklyChartObj.dispose()
      this.monthlyChartObj && this.monthlyChartObj.dispose()
      this.inspectionCompareChartObj && this.inspectionCompareChartObj.dispose()
      this.unqualifiedRateChartObj && this.unqualifiedRateChartObj.dispose()
    }
  }
}
</script>

<style scoped>
/* 基础容器样式 */
.dashboard-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.date-picker {
  width: 300px;
}

.current-time {
  color: #64748b;
  font-size: 14px;
}

.refresh-btn {
  background-color: #f1f5f9;
  color: #64748b;
  border: none;
}

/* 原生CSS hover写法 */
.refresh-btn:hover {
  background-color: #e2e8f0;
}

/* 统计卡片样式 */
.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-title {
  font-size: 14px;
  color: #64748b;
}

.card-icon {
  font-size: 20px;
}

.card-shipment .card-icon {
  color: #3b82f6;
}

.card-arrival .card-icon {
  color: #10b981;
}

.card-inspect-total .card-icon {
  color: #8b5cf6;
}

.card-unqualified-total .card-icon {
  color: #ef4444;
}

.card-qualified-rate .card-icon {
  color: #f59e0b;
}

.card-value {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 8px;
}

.digital-value {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
}

.unit {
  color: #64748b;
  font-size: 14px;
}

.card-footer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.trend-up {
  color: #10b981;
}

.trend-down {
  color: #ef4444;
}

.compared {
  color: #94a3b8;
}

/* section标题样式 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 30px 0 16px;
  padding-left: 4px;
  border-left: 3px solid #3b82f6;
}

/* 产品检验详情卡片 */
.inspection-detail-cards {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.detail-card {
  flex: 1;
  min-width: 180px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-top: 3px solid var(--card-color);
}

.detail-card-header {
  margin-bottom: 16px;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #1e293b;
}

.detail-card-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
}

.item-label {
  color: #64748b;
  font-size: 14px;
}

.item-value {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

.unqualified {
  color: #ef4444;
}

.rate {
  color: var(--card-color);
}

/* 图表区域样式 */
.charts-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.chart-card {
  flex: 1;
  min-width: 400px;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f1f5f9;
}

.chart-header span {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

.chart-type-select {
  width: 140px;
}

.chart-container {
  position: relative;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 表格和进度环样式 */
.scroll-board {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 200px;
  font-size: 12px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
}

.percentage-container {
  position: absolute;
  bottom: 30px;
  right: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.percentage-text {
  margin-top: 8px;
  font-size: 14px;
  color: #64748b;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .charts-row {
    flex-direction: column;
  }

  .chart-card {
    min-width: 100%;
  }

  .stats-cards {
    flex-direction: column;
  }

  .inspection-detail-cards {
    flex-direction: column;
  }

  .header-controls {
    flex-wrap: wrap;
  }

  .date-picker {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>
